package com.starlight.flower_server.infrastructure.util;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class ImageUtil {
    public static void main(String[] args) throws IOException {
        String imagePath ="C:\\Users\\AlexHeller\\Desktop\\Screenshot_VirtualDesktop.Android_2023.02.16-11.33.57.594_458.jpeg";
        File file = new File(imagePath);
        try {
            String fileString = imageToBase64(file);
            System.out.println(fileString);
            //base64ToImage(fileString,"C:\\Users\\AlexHeller\\Desktop\\converted_image.jpeg");
        }
        catch (IOException e){
            e.printStackTrace();
        }

    }
    /**
     * 将指定路径的图片转换成Base64字符串
     *
     * @param file 图片
     * @return Base64字符串
     * @throws IOException 如果读取文件时出错
     */
    public static String imageToBase64(File file) throws IOException {
        byte[] bytes = new byte[(int) file.length()];
        FileInputStream fis = new FileInputStream(file);
        fis.read(bytes);
        fis.close();
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * 将Base64字符串转换为图片并保存到指定路径
     *
     * @param base64String Base64字符串
     * @param savePath     保存路径
     * @throws IOException 如果写入文件时出错
     */
    public static void base64ToImage(String base64String, String savePath) throws IOException {
        byte[] bytes = Base64.getDecoder().decode(base64String.getBytes(StandardCharsets.UTF_8));
        FileOutputStream fos = new FileOutputStream(savePath);
        fos.write(bytes);
        fos.close();
    }
}
